package com.cloudlead.common.worker.impl;

import java.util.Arrays;

import com.cloudlead.common.worker.ActionContext;
import com.cloudlead.common.worker.Interceptor;
import com.cloudlead.common.worker.InterceptorChain;

public class InterceptorChainImpl implements InterceptorChain {

	private final Interceptor[] interceptors;
	private int index = 0;

	InterceptorChainImpl(Interceptor[] interceptors) {
		// 拦截器排序
		Arrays.sort(interceptors, new InterceptorOrderComparator());
		this.interceptors = interceptors;
	}

	@Override
	public void process(final ActionContext actionConfig) throws Exception{
		if (index == interceptors.length) {
			// 执行动作
			actionConfig.setResponse(actionConfig.getAction().execute(actionConfig.getRequest()));
		} else {
			index++;
			interceptors[index - 1].intercept(actionConfig, this);
		}

	}

}
